<?php

namespace App\Models\Traits;

use App\Models\User;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

trait BelongsToUser
{
    /**
     * Notes   : 所属用户
     *
     * @Date   : 2022/12/14 13:16
     * @Author : <Jason.C>
     * @return BelongsTo
     */
    public function user(): BelongsTo
    {
        return $this->belongsTo(User::class)
            ->withDefault([
                'nickname' => '00000000000',
            ]);
    }

    /**
     * Notes   : 插入数据库的时候，可以直接指定 user = User
     *
     * @Date   : 2023/3/30 11:38
     * @Author : <Jason.C>
     * @param  User  $user
     */
    public function setUserAttribute(User $user): void
    {
        $this->attributes['user_id'] = $user->getKey();
    }

    /**
     * Notes   : 用户作用域
     *
     * @Date   : 2023/3/30 11:38
     * @Author : <Jason.C>
     * @param  Builder  $query
     * @param  User|int  $user
     */
    public function scopeOfUser(Builder $query, User|int $user): void
    {
        if ($user instanceof User) {
            $query->where('user_id', $user->getKey());
        } else {
            $query->where('user_id', $user);
        }
    }
}
